package com.example.administrator.szb.activity.myyewu;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.BusinessBean;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.QTLog;
import com.example.administrator.szb.util.Toasts;
import com.example.zhouwei.library.CustomPopWindow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/10/10.
 */

public class YWXQActivity extends BaseActivity {
    @Bind(R.id.ywxq_no_image_fh)
    ImageView ywxqNoImageFh;
    @Bind(R.id.ywxq_no_text_title)
    TextView ywxqNoTextTitle;
    @Bind(R.id.ywxq_no_recyclerview)
    RecyclerView ywxqNoRecyclerview;
    @Bind(R.id.ywxq_no_edit_xgms)
    EditText ywxqNoEditXgms;
    @Bind(R.id.ywxq_no_text_zs)
    TextView ywxqNoTextZs;
    @Bind(R.id.ywxq_no_xgms)
    LinearLayout ywxqNoXgms;

    int id;//业务id
    String title;//业务名称
    int id_choose;//次级id

    BusinessBean businessBean;
    BusinessBean businessBean_choose;//次级业务
    BaseAdapter<BusinessBean.DataBean> adapter;
    @Bind(R.id.ywxq_no_button_bc)
    Button ywxqNoButtonBc;

    CustomPopWindow popWindow;//弹出框
    private BaseAdapter<BusinessBean.DataBean> adapter_choose;

    ArrayList<String> ywxq_info = new ArrayList<>();
    HashMap<Integer,String> ywxq_info_map = new HashMap<Integer,String>(){
        String info="";
        @Override
        public String toString() {
            Set<Integer> keySet = ywxq_info_map.keySet();
            //有了Set集合就可以获取其迭代器，取值
            Iterator<Integer> it = keySet.iterator();
            while (it.hasNext())
            {
                Integer i = it.next();
                String s = ywxq_info_map.get(i);
                info = info +s;

            }
            return info;
        }
    };
    HashMap<Integer,BusinessBean> save_business_choose = new HashMap<>();//用于保存请求过的数据

    HashMap<Integer,HashMap<Integer,Integer>> sava_choose_map  = new HashMap<>();

    TextView info_text;//选择后item展示的信息
    int position_list;//记录那个位置被点击

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wyxq_activity);
        ButterKnife.bind(this);
        SampleApplicationLike.getActivitiesInstance().add(this);
        getInfo();//获取跳转页面传递过来的参数
        editListenter();//监听字数变化
    }

    private void editListenter() {
        ywxqNoEditXgms.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                ywxqNoTextZs.setText(charSequence.length()+"/150");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void getInfo() {
        Intent intent = getIntent();
        id = intent.getIntExtra("id", -1);
        title = intent.getStringExtra("title");
        ywxqNoTextTitle.setText(title);
        requestData();//请求列表数据
    }

    private void requestData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("business_id", id + "");
        String url = URLAddress.URLBASE + URLAddress.URL_Business;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, BusinessBean.class, URLAddress.URLBASE + URLAddress.URL_Business, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                businessBean = (BusinessBean) response;
                if (businessBean.getResult() == 1) {
                    initRecyclerView();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

    private void initRecyclerView() {
        ywxqNoRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        initAdapter();
        ywxqNoRecyclerview.setAdapter(adapter);
    }

    private void initAdapter() {
        adapter = new BaseAdapter<BusinessBean.DataBean>(this, businessBean.getData()) {
            @Override
            public void convert(int position, BaseViewHolder holder, BusinessBean.DataBean dataBean) {
                ((TextView) holder.getView(R.id.ywxq_no_text_item)).setText(dataBean.getTitle());
                ((TextView)holder.getView(R.id.ywxq_no_text_info_item)).setText(dataBean.getInfo());
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_ywxq_item;
            }
        };

        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onItemClick(View view, int position) {
                position_list = position;
                id_choose = businessBean.getData().get(position).getId();

                if (sava_choose_map.get(position_list) == null){
                    HashMap<Integer,Integer> save_isChoose = new HashMap<>();//保存是否选中
                    sava_choose_map.put(position,save_isChoose);
                }

                show(id_choose);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void show(int id_choose) {
        if (save_business_choose.get(id_choose) == null) {
            requestDataChoose(id_choose);
        }else{
            businessBean_choose = save_business_choose.get(id_choose);
            showPopupwindow(R.layout.view_popuwindow_ywxq,R.layout.wyxq_activity);
        }
    }

    private void requestDataChoose(final int id_choose) {

        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("business_id", id_choose + "");
        String jsno = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, BusinessBean.class, URLAddress.URLBASE + URLAddress.URL_Business, map, new Response.Listener() {
            @TargetApi(Build.VERSION_CODES.KITKAT)
            @Override
            public void onResponse(Object response) {
                businessBean_choose = (BusinessBean) response;
                if (businessBean_choose.getResult() == 1) {
                   // initRecyclerView();
                    save_business_choose.put(id_choose,businessBean_choose);
                    showPopupwindow(R.layout.view_popuwindow_ywxq,R.layout.wyxq_activity);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toasts.show(YWXQActivity.this, "检查网络。。。", Toast.LENGTH_SHORT);
            }
        });
    }

    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);


//        /**
//         * 如果是单选业务类型就将下面的清除确定布局移除
//         */
//        if (businessBean_choose.getData().get(0).getType() == 2){
//            popwindow_view.findViewById(R.id.view_popuwindow_ll_ywxq).setVisibility(View.GONE);
//        }
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);
        //处理popWindow 显示内容
        handleListView(popwindow_view);
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                    .setBgDarkAlpha(0.7f) // 控制亮度
                    .size(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) //设置显示的大小，不设置就默认包裹内容
                    .setFocusable(true)//是否获取焦点，默认为ture
                    .setOutsideTouchable(true)//是否PopupWindow 以外触摸dissmiss
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        }
        //显示PopupWindow

    }

    /**
     * 处理弹出的popuwindwo 业务
     * @param contentView
     */
    private void handleListView(View contentView){
        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.view_popuwindow_recycler_ywxq);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        initAdapterChoose();
        recyclerView.setAdapter(adapter_choose);
        Button cancelAll = contentView.findViewById(R.id.view_popuwindow_button_cancel);
        Button sure = contentView.findViewById(R.id.view_popuwindow_button_sure);


        cancelAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (BusinessBean.DataBean b: businessBean_choose.getData()) {
                    b.setIsChoose(0);
                }
                adapter_choose.notifyDataSetChanged();
            }
        });

        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean flag = true;
                String info = "";
                //获取map集合中的所有键的Set集合
                Set<Integer> keySet = sava_choose_map.get(position_list).keySet();
                //有了Set集合就可以获取其迭代器，取值
                Iterator<Integer> it = keySet.iterator();
               try{
                   while (it.hasNext())
                   {
                       Integer i = it.next();
                       Integer s = sava_choose_map.get(position_list).get(i);
                       if (s == 1){
                           /**
                            * 如果已经加入次级id,就不再加入
                            */
                           for (String id : ywxq_info) {
                               if(id.equals(businessBean_choose.getData().get(i).getId()+"")){
                                   flag = false;
                               }
                           }
                           if (flag) {
                               ywxq_info.add(businessBean_choose.getData().get(i).getId()+"");
                           }
                           info = info + businessBean_choose.getData().get(i).getTitle()+"、";
                       }else{
                           ywxq_info.remove(businessBean_choose.getData().get(i).getId()+"");
                       }
                       businessBean_choose.getData().get(i).setIsChoose(s);
                   }
               }catch (Exception e){

               }

               if (!TextUtils.isEmpty(info)){
                   businessBean.getData().get(position_list).setInfo("已选择");
               }

                adapter.notifyDataSetChanged();
                popWindow.dissmiss();
            }
        });

    }

    private void initAdapterChoose() {
        adapter_choose = new BaseAdapter<BusinessBean.DataBean>(this,businessBean_choose.getData()) {
            @Override
            public void convert(final int position, BaseViewHolder holder, final BusinessBean.DataBean dataBean) {

                isMore(position,dataBean);//判断是不是多选项


                ((TextView)holder.getView(R.id.ywxq_no_popuwindow_text_item)).setText(dataBean.getTitle());
                if(dataBean.getIsChoose() == 0){
                    ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(false);
                }else{
                    ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(true);
                }

                ((CheckBox)holder.getView(R.id.ywgl_no_popuwindow_checkbox_szgl)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b) {
                            for (int j=0;j<businessBean_choose.getData().size();j++){
                                if (position!=j&&businessBean_choose.getData().get(j).getIs_repeal()==1){
                                    sava_choose_map.get(position_list).put(j,0);
                                    businessBean_choose.getData().get(j).setIsChoose(0);
                                }
                            }


                            if (dataBean.getIs_repeal()==1){
                                QTLog.e("ssssss");
                                for (int i=0;i<businessBean_choose.getData().size();i++){
                                    businessBean_choose.getData().get(i).setIsChoose(0);
                                    sava_choose_map.get(position_list).clear();
                                }

                            }

                            if (businessBean_choose.getData().get(position).getIsMore() == 2){
                                for (int i = 0; i < businessBean_choose.getData().size(); i++) {
                                    businessBean_choose.getData().get(i).setIsChoose(0);
                                }
                                businessBean_choose.getData().get(position).setIsChoose(1);

                                adapter_choose.notifyDataSetChanged();
                                sava_choose_map.get(position_list).put(position,1);

                            }
                            else if (businessBean_choose.getData().get(position).getIsMore() == 1){

                                for (int i = 0; i < businessBean_choose.getData().size(); i++) {
                                    if (businessBean_choose.getData().get(i).getType() == 2){
                                        businessBean_choose.getData().get(i).setIsChoose(0);
                                    }
                                }
                                businessBean_choose.getData().get(position).setIsChoose(1);

                                adapter_choose.notifyDataSetChanged();
                                sava_choose_map.get(position_list).put(position,1);

                            }else if(businessBean_choose.getData().get(position).getIsMore() == 3){
//                                for (int i = 0; i < businessBean_choose.getData().size(); i++) {
//                                    businessBean_choose.getData().get(i).setIsChoose(0);
//                                }
//                                businessBean_choose.getData().get(position).setIsChoose(1);
//
//                                adapter_choose.notifyDataSetChanged();
//                                sava_choose_map.get(position_list).put(position,1);
                                for (int i = 0; i < businessBean_choose.getData().size(); i++) {
                                    businessBean_choose.getData().get(i).setIsChoose(1);
                                }


                                adapter_choose.notifyDataSetChanged();
                                sava_choose_map.get(position_list).put(position,1);
                            }

                            //businessBean_choose.getData().get(position).setIsChoose(1);
                        }else {
                            sava_choose_map.get(position_list).put(position,0);
                            businessBean_choose.getData().get(position).setIsChoose(0);
                        }
                    }
                });

            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_ywxq_popuwindow_item;
            }
        };

        adapter_choose.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int flag = businessBean_choose.getData().get(position).getIsChoose();

                if (flag == 1){
                    ((CheckBox)view.findViewById(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(false);
                }else if (flag == 0){
                    ((CheckBox)view.findViewById(R.id.ywgl_no_popuwindow_checkbox_szgl)).setChecked(true);
                }

            }
        });
    }

    private void isMore(int position, BusinessBean.DataBean dataBean) {
//        if (dataBean.getTitle().equals("有") || dataBean.getTitle().equals("无") || dataBean.getTitle().equals("是") || dataBean.getTitle().equals("否") || dataBean.getTitle().equals("以上均不是")){
//            businessBean_choose.getData().get(position).setIsMore(1);
//        }

        if(dataBean.getType() == 1){
            businessBean_choose.getData().get(position).setIsMore(1);
        }else if(dataBean.getType() == 2){
            businessBean_choose.getData().get(position).setIsMore(2);
        }else if(dataBean.getType() == 3){
            businessBean_choose.getData().get(position).setIsMore(3);
        }
    }

    @OnClick({R.id.ywxq_no_image_fh, R.id.ywxq_no_xgms,R.id.ywxq_no_button_bc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ywxq_no_image_fh:
                finish();
                break;
            case R.id.ywxq_no_xgms:
                break;
            case R.id.ywxq_no_button_bc:
                boolean flag = checkInfo();
                if (flag) {
                    String id_info = "";
                    for (int i = 0; i < ywxq_info.size(); i++) {
                        id_info = id_info + ywxq_info.get(i) + ",";
                    }

                    for (int i = 0; i < businessBean.getData().size(); i++) {
                        id_info = id_info + businessBean.getData().get(i).getId() + ",";
                    }
                    id_info = id_info +""+id;

                    requestSubmit(id_info);

//                    Toasts.show(this, "保存成功", Toast.LENGTH_SHORT);
//                    Intent intent = new Intent(this,YWGLNOActivity.class);
//                    intent.putExtra("title",title);
//                    startActivity(intent);
//                    finish();
                }
                break;
        }
    }

    /**
     * 提交保存的数据
     */
    private void requestSubmit(String id_info) {
        HashMap<String,String > map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",SampleApplicationLike.getUserloginInstance().getId()+"");
        map.put("business_id",id_info);
        map.put("describe",""+ywxqNoEditXgms.getText().toString().trim());

        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, URLAddress.URLBASE + URLAddress.URL_YWBQSC, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean bean = (ResultBean) response;
                if (bean.getResult() == 1){
                   // YWGLNOActivity.isVisiable.put(""+title,1);//1,代表显示已经保存
                    YWGLNOActivity_new.businessBean_yw.getData().get(getIntent().getIntExtra("position",-1)).setIsChoose(1);
                    finish();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                DialogUtil.showToast(YWXQActivity.this,"请勿输入表情等特殊性字符");
            }
        });
    }

    /**
     * 判断是不是有些属性没有选中
     */
    private boolean checkInfo() {
        for (int i = 0; i < businessBean.getData().size(); i++) {
            if (TextUtils.isEmpty(businessBean.getData().get(i).getInfo())){
                DialogUtil.showSimpleDialog(this,"请选择："+businessBean.getData().get(i).getTitle());
                return false;
            }
        }
        return true;
    }


}
